#include "widget.h"

Widget::Widget()
    : tcpClient(new QTcpSocket(this))
    , byteArray(new QByteArray)
    , faceIdentify(new FaceIdentify("7r77ADM1jRfZVbPZgsgpGfLm", "gNqQXmc5z3WSVcwbL1behUdaUSyPVeGa"))
{
    setContent();

    connect(tcpClient, &QTcpSocket::readyRead, this, &Widget::recvVideo);
    connect(tcpClient, &QTcpSocket::connected, this, &Widget::onConnected);

    connect(faceIdentify, &FaceIdentify::recvNub, this, &Widget::checkSuccess);
    connect(faceIdentify, &FaceIdentify::recvDis, this, &Widget::checkFailed);
    connect(faceIdentify, &FaceIdentify::recvErrorMsg, this, &Widget::checkError);

    connect(loginButton, &QPushButton::clicked, this, &Widget::onLoginButtonClicked);
    connect(registerButton, &QPushButton::clicked, this, &Widget::onFaceRegisterButtonClicked);
    connect(recognizeButton, &QPushButton::clicked, this, &Widget::onFaceIdentifyButtonClicked);
    connect(showButton, &QPushButton::clicked, this, &Widget::updateTableWidget);
}

Widget::~Widget() {
    tcpClient->close();
    delete byteArray;
}

void Widget::setContent() {
    QTabWidget *tabs = new QTabWidget();
    tabs->addTab(createLoginTable(), "登录");
    tabs->addTab(createCheckInTable(), "人脸打卡");
    tabs->addTab(createRecordTable(), "打卡记录");

    videoLabel = new QLabel();
    videoLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    videoLabel->setAlignment(Qt::AlignCenter);
    videoLabel->setFixedSize(380, 290);

    imageLabel = new QLabel();
    imageLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    imageLabel->setAlignment(Qt::AlignCenter);
    imageLabel->setFixedSize(380, 290);

    QSplitter *rightSplitter = new QSplitter(Qt::Vertical);
    rightSplitter->addWidget(videoLabel);
    rightSplitter->addWidget(imageLabel);

//    rightSplitter->setStretchFactor(0, 1);
//    rightSplitter->setStretchFactor(1, 1);

    QSplitter *mainSplitter = new QSplitter(Qt::Horizontal, this);
    mainSplitter->addWidget(tabs);
    mainSplitter->addWidget(rightSplitter);

//    mainSplitter->setStretchFactor(0, 1);
//    mainSplitter->setStretchFactor(1, 1);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(mainSplitter);

    setWindowTitle("人脸识别系统");
    setGeometry(600, 400, 800, 600);
}



QWidget* Widget::createLoginTable() {
    QWidget* widget = new QWidget;

    ipLineEdit = new QLineEdit(this);
    portLineEdit = new QLineEdit(this);
    loginButton = new QPushButton("登录", this);

    // 创建IP标签和输入框
     auto *ipLabel = new QLabel("IP:", this);
     auto *ipLayout = new QHBoxLayout();
     ipLayout->addWidget(ipLabel);
     ipLayout->addWidget(ipLineEdit);

     // 创建PORT标签和输入框
     auto *portLabel = new QLabel("PORT:", this);
     auto *portLayout = new QHBoxLayout();
     portLayout->addWidget(portLabel);
     portLayout->addWidget(portLineEdit);

     // 创建主布局，将各个组件添加进来
     auto *mainLayout = new QVBoxLayout(this);
     mainLayout->addLayout(ipLayout);
     mainLayout->addLayout(portLayout);
     mainLayout->addWidget(loginButton);

     widget->setLayout(mainLayout);
     return widget;
}

QWidget* Widget::createCheckInTable() {
    QWidget* widget = new QWidget;

    departmentLineEdit = new QLineEdit(this);
    nameLineEdit = new QLineEdit(this);
    infoTextEdit = new QTextEdit(this);
    registerButton = new QPushButton("人脸注册", this);
    recognizeButton = new QPushButton("人脸识别", this);

    // 创建部门标签和输入框
    auto *departmentLabel = new QLabel("部门:", this);
    auto *departmentLayout = new QHBoxLayout();
    departmentLayout->addWidget(departmentLabel);
    departmentLayout->addWidget(departmentLineEdit);

    // 创建姓名标签和输入框
    auto *nameLabel = new QLabel("姓名:", this);
    auto *nameLayout = new QHBoxLayout();
    nameLayout->addWidget(nameLabel);
    nameLayout->addWidget(nameLineEdit);

    // 设置文本框初始属性
    infoTextEdit->setReadOnly(true); // 信息文本框设置为只读

    // 创建主布局，将各个组件添加进来
    auto *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(departmentLayout);
    mainLayout->addLayout(nameLayout);
    mainLayout->addWidget(infoTextEdit);

    // 创建按钮布局
    auto *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(registerButton);
    buttonLayout->addWidget(recognizeButton);

    // 添加按钮布局到主布局
    mainLayout->addLayout(buttonLayout);

    widget->setLayout(mainLayout);
    return widget;
}

QWidget* Widget::createRecordTable() {
    QWidget* widget = new QWidget;
    tableWidget = new QTableWidget(this);
    showButton = new QPushButton("显示", this);

    // 设置表格列数和标题
    tableWidget->setColumnCount(2);
    tableWidget->setHorizontalHeaderLabels(QStringList() << "用户名" << "打卡时间");
    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 创建并配置主布局
    auto *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(tableWidget);
    mainLayout->addWidget(showButton);

    widget->setLayout(mainLayout);
    return widget;
}


void Widget::checkSuccess(QString name, double similarity)
{
    infoTextEdit->setText("人脸识别成功, " + name
                          + "欢迎回家, 相似度: " + QString::number(similarity));
}
void Widget::checkFailed()
{
    infoTextEdit->setText("人脸识别失败");
}
void Widget::checkError(QString error)
{
    infoTextEdit->setText("人脸识别失败错误原因: " + error);
}

void Widget::recvVideo()
{
    qDebug() << "enter recvVideo function, great!";

    static int flag = 0;
    int length = 0;

    if(flag == 0)
    {
        if(tcpClient->bytesAvailable() < 8)
            return;

        length = tcpClient->read(8).toInt();
        flag = 1;
    }
    else if(flag == 1)
    {
        if(tcpClient->bytesAvailable()<length)
            return;

        *byteArray = tcpClient->read(length);
        QPixmap pix;
        pix.loadFromData(*byteArray);
        videoLabel->setPixmap(pix);
        videoLabel->setScaledContents(true);
        flag = 0;
    }
}

void Widget::onLoginButtonClicked()
{

    QString ip = ipLineEdit->text();
    int port = portLineEdit->text().toInt();
    qDebug() << "Login Button clicked, got ip" << ip << "port" << port;
    tcpClient->connectToHost(ip, port);
}

void Widget::onFaceIdentifyButtonClicked()
{
    QPixmap pix;
    pix.loadFromData(*byteArray);
    imageLabel->setPixmap(pix);
    imageLabel->setScaledContents(true);
    QImage image;
    image.loadFromData(*byteArray);
    QString department = departmentLineEdit->text();
    faceIdentify->searchFace(image,department);

    SqlHelper::getInstance().insertRecord(nameLineEdit->text());
    updateTableWidget();
}

void Widget::onFaceRegisterButtonClicked()
{
    QPixmap pix;
    pix.loadFromData(*byteArray);
    imageLabel->setPixmap(pix);
    imageLabel->setScaledContents(true);
    QImage image;
    image.loadFromData(*byteArray);
    QString department = departmentLineEdit->text();
    QString name = nameLineEdit->text();
    faceIdentify->insertUser(image, department, name);
}

void Widget::getScreenshot() {
    QPoint pos = videoLabel->mapToGlobal(QPoint(0, 0));
    QSize size = videoLabel->size();
    QScreen *screen = QGuiApplication::primaryScreen();

    if (screen)
    {
        QPixmap screenshot = screen->grabWindow(0);
        QPixmap croppedScreenshot = screenshot.copy(pos.x(), pos.y(), size.width(), size.height());
        imageLabel->setPixmap(croppedScreenshot);
        imageLabel->setScaledContents(true);
    }
}

void Widget::onConnected() {
    qDebug() << "Connected to server!";
    QMessageBox::information(this, "Success", "成功连接到服务器！");
}

void Widget::updateTableWidget() {
    qDebug() << "update Table Widget succ";

    QList<QPair<QString, QString>> records = SqlHelper::getInstance().getRecords();

    tableWidget->setRowCount(0);

    for (int i = 0; i < records.size(); ++i) {
        tableWidget->insertRow(i);
        tableWidget->setItem(i, 0, new QTableWidgetItem(records[i].first));  // 设置用户名
        tableWidget->setItem(i, 1, new QTableWidgetItem(records[i].second)); // 设置打卡时间
    }
}

